<template>
  <el-drawer
    title="标题&话题生成"
    :visible.sync="show"
    direction="rtl"
    :before-close="handleClose"
    :modal-append-to-body="false"
    size="50%"
  >
    <div class="drawer-container">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="视频同步" prop="rule">
          <div class="ai-box-list">
            <div
              v-for="(item, index) in ruleList"
              :key="item.name"
              class="ai-box-item"
            >
              <div class="header flex-b align-center">
                {{ item.name }}
                <el-popover placement="bottom" width="150" trigger="click">
                  <div
                    v-if="
                      item.type !== 'input' &&
                        item.options &&
                        item.options.length
                    "
                  >
                    <div
                      v-for="child in item.options"
                      :key="child.id"
                      class="option pointer"
                      @click="handleListAdd(index, child)"
                    >
                      {{ child.word }}
                    </div>
                  </div>
                  <!-- <div v-else-if="item.type === 'input' && item.key != 4">
                    <div class="flex-c flex-v align-center">
                      <el-input v-model="inputValue" placeholder="请输入" />
                      <el-button
                        type="primary"
                        style="margin-top: 10px"
                        @click="handleOptionInput(index)"
                      >添加</el-button>
                    </div>
                  </div>
                  <div v-else-if="item.type === 'input' && item.key == 4">
                    <div class="flex-c flex-v align-center">
                      <el-input v-model="inputValue" placeholder="请输入" />
                      <el-button
                        type="primary"
                        style="margin-top: 10px"
                        @click="handleOptionReplace(index)"
                      >替换</el-button>
                    </div>
                  </div> -->
                  <div v-else>暂无内容</div>
                  <div
                    v-if="item.type !== 'input'"
                    slot="reference"
                    class="flex-e align-center pointer"
                    @click="handleCategory(item, index)"
                  >
                    选词
                    <img
                      src="@/assets/images/down-white.png"
                      alt=""
                      class="arrow"
                    >
                  </div>
                </el-popover>
              </div>
              <div class="content scorll-box" :class="{short:item.type === 'input'}">
                <div
                  v-for="(child, c) in item.list"
                  :key="c"
                  class="item nowrap pointer"
                  :title="child.word"
                >
                  {{ child.word }}
                </div>
              </div>
              <div v-if="item.type === 'input' && item.key == 4">
                <div class="flex-c flex align-center">
                  <el-input v-model="inputValue4" class="no-br" placeholder="请输入" />
                  <el-button
                    type="primary"
                    class="lg-btn"
                    style="position: relative;top: 2px;"
                    @click="handleOptionReplace(index,item.key)"
                  >替换</el-button>
                </div>
              </div>
              <div v-if="item.type === 'input' && item.key ===5" class="flex-c  align-center">
                <el-input v-model="inputValue5" placeholder="请输入" class="no-br" />
                <el-button
                  type="primary"
                  class="lg-btn"
                  style="position: relative;top: 2px;"
                  @click="handleOptionInput(index,item.key)"
                >添加</el-button>
              </div>
              <div v-if="item.type === 'input' && item.key ===6" class="flex-c  align-center">
                <el-input v-model="inputValue6" placeholder="请输入" class="no-br" />
                <el-button
                  type="primary"
                  class="lg-btn"
                  style="position: relative;top: 2px;"
                  @click="handleOptionInput(index,item.key)"
                >添加</el-button>
              </div>

              <div class="sub" :class="{'short-sub':item.type === 'input'}">
                当前{{ item.list.length }}行，最多{{ item.max }}行
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="标题规则" prop="titleRule">
          <el-select
            v-model="ruleForm.titleRule"
            class="f1 white"
            placeholder="请选择标题规则"
          >
            <el-option
              v-for="item in titleRuleList"
              :key="item.label"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="作品标题" prop="title">
          <el-button
            type="primary"
            size="small"
            @click="getTitleRuleValue(ruleForm.titleRule)"
          >一键生成</el-button>
          <div
            v-if="titleList.length"
            class="mao-input-box"
            style="margin-top: 5px"
          >
            <div v-for="(item, index) in titleList" :key="index">
              {{ item }}
            </div>
          </div>
        </el-form-item>
        <el-form-item label="话题规则" prop="topicRule">
          <div class="flex align-center mao-radio-button-list rel" style="top: 5px;">
            <mao-radio-button
              v-for="(item,index) in topicRuleList"
              :key="index"
              v-model="ruleForm.topicRule"
              :label="item.label"
              :value="item.value"
            >
              {{ item.label }}
            </mao-radio-button>
          </div>
          <!-- <el-radio-group v-model="ruleForm.topicRule" size="small">
            <el-radio-button
              v-for="(item, index) in topicRuleList"
              :key="index"
              :label="item.value"
              :value="item.value"
            >
              {{ item.label }}</el-radio-button>
          </el-radio-group> -->
        </el-form-item>
        <el-form-item label="作品话题" prop="topic">
          <el-button
            type="primary"
            size="small"
            @click="getTopicRuleValue(ruleForm.topicRule)"
          >一键生成</el-button>
          <div
            v-if="topicList.length"
            class="mao-input-box"
            style="margin-top: 5px"
          >
            <div v-for="(item, index) in topicList" :key="index">
              {{ item }}
            </div>
          </div>
        </el-form-item>
        <el-form-item label="话题位置" prop="topicPosition">
          <div class="flex align-center">
            <mao-radio
              v-for="item in positionList"
              :key="item.value.toString()"
              v-model="ruleForm.topicPosition"
              :value="item.value.toString()"
              :label="item.label"
            />
          </div>
        </el-form-item>
      </el-form>
      <div class="flex-e align-center">
        <el-button
          type="default"
          style="margin-right: 10px"
          @click="$emit('close')"
        >取消</el-button>
        <el-button type="primary" @click="submit">立即使用</el-button>
      </div>
    </div>
  </el-drawer>
</template>
<script>
import MaoRadio from '@/components/MaoRadio/index.vue'
import { getWordList, getDict } from '@/api/publish'
export default {
  components: { MaoRadio },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    dbData: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      rules: {},
      ruleForm: {
        rule: {
          prefix: {
            name: '前缀词',
            max: 50,
            current: 30,
            key: 1,
            list: [],
            dict: 'wordcategory',
            options: []
          },
          keywords: {
            name: '关键词',
            max: 50,
            key: 6,
            type: 'input',
            current: 30,
            list: [],
            options: []
          },
          suffix: {
            name: '后缀词',
            max: 50,
            current: 30,
            key: 2,
            dict: 'wordsuffixcategory',
            list: [],
            options: []
          },
          guide: {
            name: '引导语',
            max: 50,
            current: 30,
            key: 4,
            list: [],
            options: [],
            type: 'input'
          },
          benefit: {
            name: '产品优势',
            max: 50,
            current: 30,
            key: 5,
            type: 'input',
            list: [],
            options: []
          },
          interactive: {
            name: '互动语',
            max: 50,
            current: 30,
            key: 3,
            list: [],
            options: []
          }
        },
        titleRule: '',
        title: '',
        topicRule: '',
        topic: '',
        topicPosition: ''
      },
      ruleList: [],
      inputValue4: '',
      inputValue5: '',
      inputValue6: '',
      titleList: [],
      topicList: []
    }
  },
  computed: {
    positionList() {
      return [
        { label: '话题在后', value: 1 },
        { label: '话题在前', value: 0 }
      ]
    },
    topicRuleList() {
      const ramList = [
        [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [1, 2, 4], [1, 2, 5], [1, 2, 6], [2, 3, 5], [2, 3, 6], [3, 4, 6]
      ]
      const ram = Math.floor(Math.random() * 6)
      console.log(ramList[ram])
      return [
        { value: ramList[ram], label: '随机生成' },
        { value: [6], label: '关键词' },
        { value: [1, 6], label: '前缀词+关键词' },
        { value: [6, 2], label: '关键词+后缀词' },
        { value: [1, 6, 2], label: '【前缀词+关键词+后缀词】' }
      ]
    },
    titleRuleList() {
      return [
        { value: [5], label: '【产品优势】' },
        { value: [3], label: '【互动语】' },
        { value: [5, 3], label: '【产品优势+互动语】' },
        { value: [4, 5], label: '【引导语+产品优势】' },
        { value: [1, 6, 2], label: '【前缀词+关键词+后缀词】' },
        { value: [4, 5, 3], label: '【引导语+产品优势+互动语】' },
        {
          value: [1, 6, 2, 4, 5, 3],
          label: '【前缀词+关键词+后缀词】+【引导语+产品优势+互动语】'
        }
      ]
    }
  },
  watch: {
    dbData: {
      handler(val) {
        if (val.id) {
          this.handleUpdateInit()
        }
      },
      deep: true
    }
  },
  async created() {
    const arr = []
    for (const key in this.ruleForm.rule) {
      const item = this.ruleForm.rule[key]
      item.header = key
      if ((item.key && item.type !== 'input') || item.key === 4) {
        item.list = await this.getCodeList(item.key)
      }
      arr.push(item)
    }
    this.ruleList = arr
  },
  methods: {
    handleUpdateInit() {
      console.log('[dbData]', this.dbData)
      const { videoTitle, videoTopic, topicPosition } = this.dbData
      if (videoTitle) {
        this.titleList = videoTitle.split('&*&*')
      }
      if (videoTopic) {
        this.topicList = videoTopic.split('&*&*')
      }
      this.$set(this.ruleForm, 'topicPosition', (topicPosition || topicPosition === 0) ? topicPosition.toString() : '')
    },
    handleListAdd(index, child) {
      if (this.ruleList[index]) {
        const item = this.ruleList[index]
        if (!item.list.find((ele) => ele.id === child.id)) {
          item.list.push(child)
        }
      }
    },
    handleOptionInput(index, key) {
      if (this.ruleList[index]) {
        const item = this.ruleList[index]
        if (!item.list.find((ele) => ele.name === this['inputValue' + key])) {
          item.list.push({ word: this['inputValue' + key], id: item.inputValue })
        }
        this['inputValue' + key] = ''
        this.$set(this.ruleList, index, item)
      }
    },
    handleOptionReplace(index, key) {
      if (this.ruleList[index] && this['inputValue' + key].trim()) {
        const item = this.ruleList[index]
        let tempList = []
        if (Array.isArray(item.list)) {
          tempList = item.list.map((ele) => {
            if (ele.word) {
              ele.word = ele.word.replaceAll('XXXX', this['inputValue' + key])
            }
            return ele
          })
        }
        item.list = tempList
        this['inputValue' + key] = ''
        this.$set(this.ruleList, index, item)
      }
    },
    async handleCategory(item, index) {
      const _item = { ...item }
      if (item.dict) {
        const options = await this.getDictList(item.dict)
        _item.options = options.map(item => {
          item.word = item.title
          return item
        })
        this.$set(this.ruleList, index, _item)
      } else if (item.type !== 'input' || item.key === 4) {
        const options = await this.getCodeList('', item.key)
        _item.options = options
        this.$set(this.ruleList, index, _item)
      }
    },
    handleClose() {
      this.$emit('close')
    },
    getCodeList(key = '', category = '') {
      return new Promise((resolve) => {
        getWordList({
          attributes: key,
          category
        }).then((res) => {
          if (res.success) {
            resolve(res.result.records || [])
          } else {
            this.$message.error(res.message)
            resolve([])
          }
        })
      })
    },
    getDictList(dictCode) {
      return new Promise((resolve) => {
        getDict(dictCode).then((res) => {
          if (res.success) {
            resolve(res.result || [])
          } else {
            this.$message.error(res.message)
            resolve([])
          }
        })
      })
    },
    getTitleRuleValue(keys = []) {
      if (!(Array.isArray(keys) && keys.length)) {
        return
      }
      const totalList = []
      this.ruleList.forEach((item) => {
        if (keys.includes(item.key)) {
          totalList.push(item.list.map((child) => child.word))
        }
      })
      // 逐个匹配
      totalList.forEach((item) => {
        if (!item.length) {
          item[0] = ''
        }
      })
      this.titleList = this.serialArray(totalList)
    },
    getTopicRuleValue(keys = []) {
      console.log('getTopicRuleValue', keys)
      if (!(Array.isArray(keys) && keys.length)) {
        return
      }
      const totalList = []
      this.ruleList.forEach((item) => {
        if (keys.includes(item.key)) {
          totalList.push(item.list.map((child) => child.word))
        }
      })
      // 逐个匹配
      totalList.forEach((item) => {
        if (!item.length) {
          item[0] = ''
        }
      })
      this.topicList = this.serialArray(totalList)
    },
    submit() {
      const list = [
        {
          list: this.titleList,
          value: this.titleList.join('&*&*'),
          name: 'videoTitle'
        },
        {
          list: this.topicList,
          value: this.topicList.join('&*&*'),
          name: 'videoTopic'
        },
        this.ruleForm

      ]
      this.$emit('ok', list)
    },
    serialArray(arr = []) {
      const lengthArr = []
      const productArr = []
      const result = []
      let length = 1
      for (let i = 0; i < arr.length; i++) {
        const len = arr[i].length
        lengthArr.push(len)
        const product = i === 0 ? 1 : arr[i - 1].length * productArr[i - 1]
        productArr.push(product)
        length *= len
      }
      for (let i = 0; i < length; i++) {
        let resultItem = ''
        for (let j = 0; j < arr.length; j++) {
          resultItem += arr[j][Math.floor(i / productArr[j]) % lengthArr[j]]
        }
        result.push(resultItem)
      }
      return result
    }
  }
}
</script>
<style lang="scss" scoped>
.option {
  margin-bottom: 5px;
}
.drawer-container {
  box-sizing: border-box;
  padding: 0 20px 20px;
}
.ai-box-list {
  display: grid;
  grid-template-columns: 30% 1fr 30%;
  grid-column-gap: 30px;
  .ai-box-item {
    .header {
      height: 44px;
      border-radius: 15px 15px 0 0;
      background: rgba(0, 119, 255, 1);
      font-size: 14px;
      font-weight: 400;
      color: rgba(255, 255, 255, 1);
      box-sizing: border-box;
      padding: 0 12px;
    }
    .arrow {
      width: 10px;
      margin-left: 4px;
    }
    .item {
      font-size: 14px;
      margin-bottom: 5px;
    }
    .no-br{
      ::v-deep .el-input__inner{
        border-top-right-radius: 0;
        border-bottom-right-radius: 0;
        border-right: 0;
      }
    }
    .content {
      padding: 012px;
      height: 230px;
      border-radius: 5px;
      background: rgba(229, 229, 229, 1);
      position: relative;
      top: -6px;
      overflow-y: auto;
      font-size: 14px;
      font-weight: 400;
      line-height: 30px;
      color: rgba(0, 0, 0, 1);
    }
    .content.short{
      height: 186px;
    }
    .sub {
      font-size: 14px;
      font-weight: 400;
      color: rgba(128, 128, 128, 1);
      position: relative;
      top: -8px;
    }
    .short-sub{
      top: 0;
    }
  }
}
</style>
